﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Rung.EBook.DocFormater.Umd;
using Rung.EBook.Common.Model;

namespace Rung.EBook.UI.Controls.Panels
{
    public partial class pnProjectEdit : UserControl
    {
        private WriteInfo mWriteInfo;
        private AppendInfo mAppendInfo;
        private UmdBookBM mBookBM = new UmdBookBM();
        private ChapterBM mCurrSelectedChapter;

        public pnProjectEdit()
        {
            InitializeComponent();

            this.txbContent.KeyDown += new KeyEventHandler(UiHelper.TextBox_KeyDown);
        }

        internal pnProjectEdit(WriteInfo infoWriter, AppendInfo appendInfo)
            : this()
        {
            this.mWriteInfo = infoWriter;
            this.mAppendInfo = appendInfo;
        }

        private void pnProjectEdit_Load(object sender, EventArgs e)
        {
            this.Dock = DockStyle.Fill;
        }

        // 打开工程
        private void btnOpenProject_Click(object sender, EventArgs e)
        {
            using (OpenFileDialog dialog = new OpenFileDialog())
            {
                dialog.Title = "载入工程";
                dialog.CheckPathExists = true;
                dialog.Multiselect = false;
                dialog.DefaultExt = "ebp";
                dialog.Filter = "RungEBook项目文件|*.ebp";
                dialog.InitialDirectory = Rung.EBook.Common.Driver.StaticFunctions.GetProjectFolderPath();

                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    string filePath = dialog.FileName;

                    try
                    {
                        this.mBookBM.LoadByProject(filePath);

                        this.mWriteInfo("载入工程成功。", InfoType.Success);
                        this.RenderByBookBM();
                    }
                    catch (Exception ex)
                    {
                        this.mWriteInfo("载入工程失败：" + ex.Message, InfoType.Errer);
                    }
                }
            }
        }

        // 将 mBook 变量中的值赋予界面控件。
        private void RenderByBookBM()
        {
            //tbAuthor.Text = this.mBookBM.Author;
            //tbBookTitle.Text = this.mBookBM.Title;
            //tbGender.Text = this.mBookBM.Kind;
            //tbPublisher.Text = this.mBookBM.Publisher;
            //tbVendor.Text = this.mBookBM.Vendor;

            lbChapters.Items.Clear();
            foreach (ChapterBM bm in this.mBookBM.Chapters)
            {
                lbChapters.Items.Add(bm);
            }
        }

        // 选择章节
        private void lbChapters_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (lbChapters.SelectedIndex < 0) return;

            // 自动保存上次选中的章节
            if (this.cbAutoSave.Checked && this.mCurrSelectedChapter != null)
            {
                // 标题
                if (this.mCurrSelectedChapter.Title != txbNewChapterTitle.Text)
                {
                    int index = lbChapters.SelectedIndex;

                    this.mCurrSelectedChapter.Title = txbNewChapterTitle.Text;
                    lbChapters.DataSource = this.mBookBM.Chapters;

                    lbChapters.SelectedIndex = index;
                }

                // 正文
                if (this.txbContent.BackColor == Color.Pink)// 说明有变化
                {
                    this.mCurrSelectedChapter.Content = this.txbContent.Text;
                    this.mWriteInfo(string.Format("保存章节【{0}】成功。", this.mCurrSelectedChapter.Title), InfoType.Success);
                }
            }

            this.mCurrSelectedChapter = lbChapters.SelectedItem as ChapterBM;
            if (this.mCurrSelectedChapter != null)
            {
                txbNewChapterTitle.Text = mCurrSelectedChapter.ToString();
                txbContent.Text = mCurrSelectedChapter.Content;

                // 背景色改回来
                txbContent.BackColor = SystemColors.Window;
            }
        }

        // 正文修改，背景变色
        private void txbContent_TextChanged(object sender, EventArgs e)
        {
            ChapterBM cBM = lbChapters.SelectedItem as ChapterBM;

            //if (cBM != null && this.txbContent.Text != cBM.Content)
            if (cBM != null && string.CompareOrdinal(this.txbContent.Text, cBM.Content) != 0)
                txbContent.BackColor = Color.Pink;
            else
                txbContent.BackColor = SystemColors.Window;
        }

        // 保存工程
        private void btnSaveProject_Click(object sender, EventArgs e)
        {
            using (SaveFileDialog dialog = new SaveFileDialog())
            {
                dialog.Title = "保存工程";
                dialog.AddExtension = true;
                dialog.CheckPathExists = true;
                dialog.DefaultExt = "ebp";
                dialog.Filter = "RungEBook工程文件|*.ebp";
                dialog.InitialDirectory = Rung.EBook.Common.Driver.StaticFunctions.GetProjectFolderPath();

                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    ProjectBM pBM = new ProjectBM();
                    pBM.Book = this.mBookBM;
                    pBM.BookClass = this.mBookBM.GetType().FullName;
                    pBM.BuildTime = DateTime.Now;

                    try
                    {
                        pBM.Save(dialog.FileName);
                        this.mWriteInfo("保存工程成功。", InfoType.Success);
                    }
                    catch (Exception ex)
                    {
                        this.mWriteInfo("保存工程失败：" + ex.Message, InfoType.Errer);
                    }
                }
            }
        }

        #region 章节列表操作
        private void btnChapterAdd_Click(object sender, EventArgs e)
        {
            string title = txbNewChapterTitle.Text.Trim();
            string content = txbContent.Text.Trim();

            if (string.IsNullOrEmpty(title))
            {
                this.mWriteInfo("待添加的章节标题不能为空。", InfoType.Warning);
                return;
            }
            else if (string.IsNullOrEmpty(content))
            {
                this.mWriteInfo("待添加的章节内容不能为空。", InfoType.Warning);
                return;
            }
            else if (this.mBookBM.Chapters.Find(delegate(ChapterBM bm) { return bm.Title == title; }) != null)
            {
                this.mWriteInfo("标题不能重复。", InfoType.Warning);
                return;
            }

            ChapterBase cBM = new ChapterBase
            {
                Index = this.lbChapters.Items.Count - 1,
                Title = title,
                Content = content
            };

            mBookBM.AppendChapter(cBM);
            lbChapters.Items.Add(cBM);

            this.mWriteInfo(string.Format("添加章节【{0}】，正文{1}字。", cBM.Title, cBM.Content.Length), InfoType.Success);
        }

        private void btnChapterDelete_Click(object sender, EventArgs e)
        {
            if (lbChapters.SelectedIndex < 0) return;

            ChapterBM cBM = lbChapters.SelectedItem as ChapterBM;
            if (cBM != null)
            {
                this.mBookBM.RemoveChapter(cBM);
                lbChapters.Items.RemoveAt(lbChapters.SelectedIndex);

                this.mWriteInfo(string.Format("删除章节【{0}】。", cBM.Title), InfoType.Success);
            }
        }

        private void btnChapterUp_Click(object sender, EventArgs e)
        {
            if (lbChapters.SelectedIndex <= 0) return;

            this.MoveListBoxItem(lbChapters, lbChapters.SelectedItem, -1);
        }

        private void btnChapterDown_Click(object sender, EventArgs e)
        {
            if (lbChapters.SelectedIndex < 0) return;
            if (lbChapters.SelectedIndex == lbChapters.Items.Count - 1) return;

            this.MoveListBoxItem(lbChapters, lbChapters.SelectedItem, 1);
        }

        private void btnChapterClear_Click(object sender, EventArgs e)
        {
            this.mBookBM.Chapters.Clear();
            this.lbChapters.Items.Clear();
            this.txbNewChapterTitle.Text = this.txbContent.Text = string.Empty;

            this.mWriteInfo("清除本书所有章节。", InfoType.Success);
        } 

        /// <summary>
        /// 移动菜单项
        /// </summary>
        /// <param name="lb">菜单列表控件</param>
        /// <param name="item">待移动项</param>
        /// <param name="step">移动步长</param>
        private void MoveListBoxItem(ListBox lb, object item, int step)
        {
            string title = item.ToString();
            int index = this.mBookBM.Chapters.FindIndex(delegate(ChapterBM bm) { return bm.Title == title; });
            if (index >= 0)
            {
                ChapterBase cBM = this.mBookBM.Chapters[index];
                ChapterBase downBM = this.mBookBM.Chapters[index + step];
                cBM.Index = cBM.Index + step;
                downBM.Index = downBM.Index - step;

                this.mBookBM.Chapters.Sort(delegate(ChapterBM x, ChapterBM y) { return x.Index - y.Index; });

                this.lbMenu_Bind();
            }
        }

        /// <summary>
        /// （重新）绑定章节菜单的数据。
        /// </summary>
        private void lbMenu_Bind()
        {
            this.lbChapters.Items.Clear();

            this.lbChapters.DataSource = this.mBookBM.Chapters;
        }
        #endregion

        // 内容编辑 - 替换
        private void btnEditReplace_Click(object sender, EventArgs e)
        {
            txbContent.Text = txbContent.Text.Replace(txbEditReplace1.Text, txbEditReplace2.Text);
        }
    }
}
